
package com.jf.cloud.flow.config;


import cn.hutool.core.io.IoUtil;
import org.lionsoul.ip2region.xdb.Searcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;

/**
 * 获取IP
 * @author zz
 * @date 2021-06-02
 */
@Configuration
public class Ip2RegionConfig {

    private static final Logger log = LoggerFactory.getLogger(Ip2RegionConfig.class);

    @Bean(destroyMethod = "close")
    public Searcher searcher() throws IOException {
        // 获取ip库路径
        ClassPathResource classPathResource = new ClassPathResource("ip2region.xdb");
        if (classPathResource.getClassLoader() == null){
            log.error("ip2region.xdb 存储路径发生错误，没有被发现");
            return null;
        }
        InputStream inputStream = classPathResource.getInputStream();
        // 1、从 dbPath 加载整个 xdb 到内存。
        byte[] cBuff = IoUtil.readBytes(inputStream);

        // 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
        Searcher searcher = null;
        try {
            searcher = Searcher.newWithBuffer(cBuff);
        } catch (Exception e) {
            System.out.printf("failed to create content cached searcher: %s\n", e);
        }
        return searcher;
    }
}
